package com.sinosoft.call.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.sinosoft.call.entity.CallConfig;

import com.sinosoft.call.service.CallService;
import com.sinosoft.vo.http.Result;
@Service("mongoCallService")
public class MongoCallServiceImpl implements CallService{
	private HttpHeaders headers;
	@Autowired
	private RestTemplate restTemplate;
	@Override
	public Result callService(CallConfig callConfig, JSON params) {
		MultiValueMap<String, Object> requestParam = new LinkedMultiValueMap<>();
		JSONObject param = (JSONObject) params;
		Set<String> keySet = param.keySet();
		for (String key : keySet) {
			requestParam.add(key, param.get(key));
		}
		
    	HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(requestParam,getHttpHeaders());
    	ResponseEntity<String> obj = restTemplate.exchange(callConfig.getCallurl(), HttpMethod.valueOf(callConfig.getMenthod()), requestEntity, String.class);
		String result = obj.getBody();
		return pubResultJSON(true, "", result);
	}
	public HttpHeaders getHttpHeaders() {
		if (headers == null) {
			headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		}
		return headers;
	}
	public Map<String, String> getPathValue(String url, JSONObject param) {
		Map<String, String> re = new HashMap<String, String>();
		Pattern p = Pattern.compile("\\{[^\\{]*\\}");
		Matcher q = p.matcher(url);
		while (q.find()) {
			String key = q.group(0).replaceAll("\\{|\\}", "");
			re.put(key, param.getString(key));
		}
		return re;
	}
}
